<template>
  <div>
    <a-form-model ref="ha_datasourceForm" :rules="rules" :model="ha_datasource">
      <a-form-model-item required :label-col="labelCol" :wrapper-col="wrapperCol" label="名称" prop="name">
        <a-input
          v-if="!isView"
          allow-clear
          v-model="ha_datasource.name"
          :maxLength="100"
          placeholder="请输入名称"
        />
        <span v-text="ha_datasource.name" v-else></span>
      </a-form-model-item>
      <a-form-model-item required :label-col="labelCol" :wrapper-col="wrapperCol" label="数据库类型" prop="dbtype">
        <a-select :disabled="isView" v-model="ha_datasource.dbtype" :options="dataSourceType" />
      </a-form-model-item>
      <a-form-model-item required :label-col="labelCol" :wrapper-col="wrapperCol" label="库名" prop="schema">
        <a-input
          v-if="!isView"
          allow-clear
          v-model="ha_datasource.schema"
          :maxLength="100"
          placeholder="请输入库名"
        />
        <span v-text="ha_datasource.schema" v-else></span>
      </a-form-model-item>
      <a-form-model-item required :label-col="labelCol" :wrapper-col="wrapperCol" label="地址" prop="url">
        <a-input
          v-if="!isView"
          allow-clear
          v-model="ha_datasource.url"
          :maxLength="500"
          placeholder="请输入地址"
        />
        <span v-text="ha_datasource.url" v-else></span>
      </a-form-model-item>
      <a-form-model-item required :label-col="labelCol" :wrapper-col="wrapperCol" label="账号" prop="username">
        <a-input
          v-if="!isView"
          allow-clear
          v-model="ha_datasource.username"
          :maxLength="100"
          placeholder="请输入账号"
        />
        <span v-text="ha_datasource.username" v-else></span>
      </a-form-model-item>
      <a-form-model-item required :label-col="labelCol" :wrapper-col="wrapperCol" label="密码" prop="pass">
        <a-input-password
          v-if="!isView"
          allow-clear
          v-model="ha_datasource.pass"
          :maxLength="100"
          placeholder="请输入密码"
        />
        <span v-else><b>......</b></span>
      </a-form-model-item>
      <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="是否默认" prop="isdefault">
        <a-tooltip>
          <template slot="title">
            如果之前有默认，保存后会覆盖之前的默认
          </template>
          <a-switch
            :disabled="isView"
            checked-children="是"
            v-model="isdefault"
            un-checked-children="否"
            default-checked
          />
        </a-tooltip>
      </a-form-model-item>
      <a-form-model-item>
        <div style="text-align: center;">
          <a-button type="primary" icon="sync" :style="{ marginRight: '8px' }" :loading="ctloading" @click="connection" v-if="!isView">
            测试连接
          </a-button>
          <a-button :style="{ marginRight: '8px' }" icon="close" @click="onClose">
            关闭
          </a-button>
          <a-button @click="onSubmit" icon="save" :loading="loading" v-if="!isView">
            保存
          </a-button>
        </div>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
/* eslint-disable */
import {
  saveha_datasource,
  viewha_datasource,
  connectionha_datasource
} from '@/api/workflow/ha_datasource.js'
// 没用到枚举请删除
import { queryEnumerationValuesByName } from '@/api/base/enumeration'

export default {
  data() {
    return {
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      loading: false, //按钮显示
      isView: false, //是否查看
      ha_datasource: {
        id: '',
        name: '',
        isdefault: '',
        dbtype: 'MySQL',
        url:
          'jdbc:mysql://159.75.12.108:3308/admin?useSSL=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true',
        username: '',
        pass: '',
        schema: 'admin'
      }, //表单所用的数据源信息
      isdefault: false,
      rules: {
        name: [{ required: true, message: '请输入名称', whitespace: true, trigger: 'change' }],
        dbtype: [{ required: true, message: '请选择数据库类型', whitespace: true, trigger: 'change' }],
        schema: [{ required: true, message: '请输入数据库名', whitespace: true, trigger: 'change' }],
        url: [{ required: true, message: '请输入地址', whitespace: true, trigger: 'change' }],
        username: [{ required: true, message: '请输入账号', whitespace: true, trigger: 'change' }],
        pass: [{ required: true, message: '请输入密码', whitespace: true, trigger: 'change' }]
      },
      dataSourceType: [
        { label: 'MySQL', value: 'MySQL' },
        { label: 'PostgreSQL', value: 'PostgreSQL' },
        { label: 'Oracle', value: 'Oracle' },
      ],
      ctloading: false
    }
  },
  created() {
    // 没有用到枚举请删除
    this.findEnumByName()
  },
  methods: {
    /**
     *  查询枚举值,没有用到枚举请删除
     */
    findEnumByName() {
      const parameter = []
      parameter.forEach(item => {
        queryEnumerationValuesByName({ enName: item.enumName }).then(res => {
          console.log('query' + item.enumName, res.data)
          this[`${item.enname}List`] = res.data
          //this[`${item.enname}List`].unshift({ id: '', description: '全部' })
        })
      })
    },
    /**
     * 调用父组件的方法收起抽屉
     */
    onClose() {
      this.$emit('close')
    },
    /**
     * 提供给父组件调用
     * 点击新增进入时重置表单数据
     */
    resetha_datasource() {
      this.isView = false
      this.resetForm()
    },
    /**
     * 提供给父组件调用
     * 查询用户信息
     */
    findha_datasourceById(id, isView) {
      this.isView = isView
      this.resetForm()

      viewha_datasource(id).then(res => {
        // console.log('******', res)
        this.ha_datasource = res.data
        this.isdefault = this.ha_datasource.isdefault == 3200
        /**
         *  枚举如果不能显示中文打开下面的代码
         */
      })
    },
    /**
     * 重置表单
     */
    resetForm() {
      this.$refs.ha_datasourceForm.resetFields()
    },
    /**
     * 测试连接
     */
    connection() {
      this.$refs.ha_datasourceForm.validate(valid => {
        this.ctloading = true
        if (valid) {
          delete this.ha_datasource.primaryKey
          this.ha_datasource.isdefault = this.isdefault ? 3200 : 3201
          if(!this.ha_datasource.id){
            delete this.ha_datasource.id
          }
          connectionha_datasource(this.ha_datasource).then(res => {
            console.log('connection res', res)
            if (res.code !== 0 && !res.data) {
              this.$message.error('连接失败！')
              this.ctloading = false
            } else {
              this.$message.success('测试连接成功！')
              this.ctloading = false
            }
          })
        } else {
          this.ctloading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            //console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },
    /**
     * 提交表单
     */
    onSubmit() {
      this.$refs.ha_datasourceForm.validate(valid => {
        this.loading = true
        if (valid) {
          delete this.ha_datasource.primaryKey
          this.ha_datasource.isdefault = this.isdefault ? 3200 : 3201
          if(!this.ha_datasource.id){
            delete this.ha_datasource.id
          }
          console.log('submit!', this.ha_datasource)
          const savem = this.$message.loading('数据正在保存中...', 0)
          saveha_datasource(this.ha_datasource).then(res => {
            if (res.code !== 0) {
              setTimeout(savem, 0)
              this.$message.error('表单所用的数据源保存失败')
              this.loading = false
            } else {
              setTimeout(savem, 0)
              this.$message.success('保存成功')
              this.$emit('reloadList')
              this.$emit('close')
              this.loading = false
            }
          })
        } else {
          this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            //console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" src="@/style/base.less"></style>
